// Copyright (C) 2012 Yury Bychenkov (http://bychenkov.com).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//  - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//  - Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//  - Neither the name of Yury Bychenkov nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "index.h"

IndexBuilder::IndexBuilder(uint8* data_, uint dataSize_, uint chunkSize_):
	chunkSize(chunkSize_ & ~0xFU),
	baseIndex(0),
	data(data_),
	dataSize(dataSize_),
	dataPos(0),
	capacity(0xFFFF),
	count(0)
{
	values = new uint32[capacity];
}
	

IndexBuilder::~IndexBuilder() {
	delete values;
}

uint IndexBuilder::build() {
	while (count > 0) {
		if (!buildChunk()) {
			return 0;
		}
	}
	return dataPos;
}


bool IndexBuilder::buildChunk() {
	const int PAYLOAD_BITS = (chunkSize - sizeof(Index::Header)) * 8;

	if (dataPos + chunkSize > dataSize) {
		return false;
	}

	uint32 minValue = values[0];
	uint32 maxValue = values[0];
	int bitCount = 0; // TODO =0 Optimize long (NULL) sequences
	int chunkCount = 1;

	while (chunkCount < count) {
		int k;

		uint32 v = values[chunkCount];
		if (minValue > v) {
			k = NumberUtil::numberOfSignificantBits(maxValue - v);
		} else if (maxValue < v) {
			k = NumberUtil::numberOfSignificantBits(v - minValue);
		} else {
			k = bitCount;
		}

		if (k * (chunkCount + 1) > PAYLOAD_BITS) {
			break;
		}

		if (minValue > v) {
			minValue = v;
		} else if (maxValue < v) {
			maxValue = v;
		}

		bitCount = k;
		chunkCount++;
	}

	uint8* chunk = data + dataPos;

	// Header
	Index::Header* header = (Index::Header*) chunk;

	memset(header, 0, sizeof(Index::Header));

	header->baseIndex = (uint32) baseIndex;
	header->count = (uint16) chunkCount;
	header->bitCount = (uint8) bitCount;
	header->minValue = minValue;
	header->maxValue = maxValue;

	// Payload
	uint64* p = (uint64*)(chunk + sizeof(Index::Header));
	uint64 w = 0;
	int bitsAvailable = NumberUtil::UINT64_BITS;
	for (int i = 0; i < chunkCount; i++) {
		uint64 v = values[i] - minValue;
		w |= v << (NumberUtil::UINT64_BITS - bitsAvailable);
		if (bitsAvailable > bitCount) {
			bitsAvailable -= bitCount;
		} else {
			*p++ = w;
			w = v >> bitsAvailable;
			bitsAvailable = NumberUtil::UINT64_BITS - (bitCount - bitsAvailable);			
		}
	}

	if (bitsAvailable < NumberUtil::UINT64_BITS) {
		*p++ = w;
	}

	if (((uint8*) p) - chunk < chunkSize) {
		memset(p, 0, chunkSize - (((uint8*) p) - chunk));
	}

	count -= chunkCount;
	if (count > 0) {
		memmove(values, values + chunkCount, sizeof(*values) * count);
	}

	dataPos += chunkSize;
	baseIndex += chunkCount;

	return true;
}
